package com.onlinelibrary.activities.main.ui.me;

import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.content.Intent;
import android.content.SharedPreferences;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.Toast;

import androidx.databinding.BindingAdapter;
import androidx.fragment.app.FragmentActivity;
import androidx.lifecycle.MutableLiveData;
import androidx.lifecycle.ViewModel;

import com.onlinelibrary.R;
import com.onlinelibrary.activities.App;
import com.onlinelibrary.activities.collection.CollectActivity;
import com.onlinelibrary.activities.commentsettings.CommentSettingsActivity;
import com.onlinelibrary.activities.login.LoginActivity;
import com.onlinelibrary.activities.modify.ModifyActivity;
import com.onlinelibrary.activities.setting.SettingActivity;
import com.onlinelibrary.activities.star.StarActivity;
import com.onlinelibrary.activities.web.WebActivity;
import com.onlinelibrary.adapter.MeAdapter;
import com.onlinelibrary.bean.MeListBean;
import com.onlinelibrary.databinding.FragmentMeBinding;
import com.onlinelibrary.utils.Http;
import com.onlinelibrary.view.CircleImageView;

import org.jetbrains.annotations.NotNull;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Response;

public class MeVM extends ViewModel {
    @SuppressLint("StaticFieldLeak")
    private static FragmentActivity requireActivity;
    private static MeFragment meFragment;
    @SuppressLint("StaticFieldLeak")
    private static FragmentMeBinding binding;
    private final List<MeListBean> data=new ArrayList<>();

    public static MutableLiveData<String>sex=new MutableLiveData<>(),
            email=new MutableLiveData<>(),
            name=new MutableLiveData<>(),
            msg=new MutableLiveData<>(),
            remarks=new MutableLiveData<>(),
            userType=new MutableLiveData<>();
    public MeVM(){
        sex.setValue("");
        name.setValue("游客");
        email.setValue("点击头像登录(登陆后显示email)");
        msg.setValue("");
        remarks.setValue("");
        userType.setValue("普通用户");
    }
    public void setBinding(FragmentMeBinding binding, MeFragment meFragment, FragmentActivity requireActivity) {
        MeVM.binding=binding;
        MeVM.requireActivity=requireActivity;
        MeVM.meFragment=meFragment;
        binding.setAdp(new MeAdapter(requireActivity,data));
        binding.meList.setOnItemClickListener((parent, view, position, id) -> {
            switch (data.get(position).name){
                case "退出登录":
                    sex.setValue("");
                    name.setValue("游客");
                    email.setValue("点击头像登录(登陆后显示email)");
                    msg.setValue("");
                    App.hasLogin=false;
                    @SuppressLint("CommitPrefEdits") SharedPreferences.Editor edit = App.sp.edit();
                    edit.putBoolean("autoLogin",false);
                    edit.putString("name","Tourist");
                    edit.apply();
                    data.clear();
                    binding.getAdp().notifyDataSetChanged();
                    break;
                case "修改个人资料":
                    meFragment.startActivityForResult(new Intent(requireActivity, ModifyActivity.class),1);
                    break;
                case "管理":
                    if (App.is_staff){
                        AlertDialog.Builder dialog=new AlertDialog.Builder(requireActivity);
                        dialog.setMessage("请选择").setNegativeButton("数据库管理", (dialog12, which) -> {
                            App.url=Http.BASE_URL+"admin/";
                            meFragment.startActivity(new Intent(requireActivity, WebActivity.class));
                        }).setNeutralButton("评论管理", (dialog1, which) -> {
                            requireActivity.startActivity(new Intent(requireActivity, CommentSettingsActivity.class));
                        }).setPositiveButton("取消",null).show();
                    }else {
                        Toast.makeText(requireActivity, "抱歉您不是管理员", Toast.LENGTH_SHORT).show();
                    }
                    break;
                case "评分":
                    meFragment.startActivity(new Intent(requireActivity, StarActivity.class));
                    break;
                case "我的收藏":
                    meFragment.startActivity(new Intent(requireActivity, CollectActivity.class));
                    break;
            }
        });
        App.autoLoginCheck(new Callback() {
            @Override
            public void onFailure(@NotNull Call call, @NotNull IOException e) { }
            @Override
            public void onResponse(@NotNull Call call, @NotNull Response response) {
                requireActivity.runOnUiThread(() -> {
                    try {
                        assert response.body() != null;
                        String res = response.body().string();
                        if (res.equals("验证成功")){
                            getMsgs();
                        }
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                });
            }
        });
    }
    @BindingAdapter("bindSex")
    public static void bindSex(ImageView imageView,MutableLiveData<String>sex){
        if (sex.getValue().equals("男")){
            imageView.setImageResource(R.drawable.male);
        }else if (sex.getValue().equals("女")){
            imageView.setImageResource(R.drawable.female);
        }else {
            imageView.setImageResource(R.drawable.sex);
        }
    }
    @BindingAdapter("bindIcon")
    public static void bindIcon(CircleImageView imageView, MutableLiveData<String>sex){
        if (sex.getValue().equals("男")){
            imageView.setImageResource(R.drawable.ic_male);
        }else if (sex.getValue().equals("女")){
            imageView.setImageResource(R.drawable.ic_female);
        }else {
            imageView.setImageResource(R.drawable.icon);
        }
    }
    public static void login(View view){
        if (!App.hasLogin) {
            meFragment.startActivityForResult(new Intent(requireActivity, LoginActivity.class), 1);
        }
    }
    public static void setting(View view){
        meFragment.startActivity(new Intent(requireActivity, SettingActivity.class));
    }
    public void onActivityResult(int resultCode) {
        if (resultCode==3){
            getMsgs();
        }
    }
    private void getMsgs() {
       App.getMsg(new Callback() {
           @Override
           public void onFailure(@NotNull Call call, @NotNull IOException e) { }
           @Override
           public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException {
               try {
                   assert response.body() != null;
                   JSONObject jo = new JSONObject(response.body().string());
                   name.postValue(jo.getString("name"));
                   sex.postValue(jo.getString("gender"));
                   email.postValue(jo.getString("email"));
                   msg.postValue("系院："+jo.getString("department")+" 学号："+jo.getString("stu_id"));
                   App.is_staff=jo.getBoolean("is_staff");
                   remarks.postValue(jo.getString("remarks"));
                   App.hasLogin=true;
                   @SuppressLint("CommitPrefEdits") SharedPreferences.Editor edit = App.sp.edit();
                   edit.putString("name",jo.getString("name"));
                   edit.apply();
                   requireActivity.runOnUiThread(() -> {
                       data.clear();
                       data.add(new MeListBean(R.drawable.msg,"修改个人资料"));
                       data.add(new MeListBean(R.drawable.collect,"我的收藏"));
                       data.add(new MeListBean(R.drawable.evalution,"评分"));
                       if (App.is_staff){
                           userType.postValue("管理员");
                           data.add(new MeListBean(R.drawable.admin,"管理"));
                       }
                       data.add(new MeListBean(R.drawable.exit,"退出登录"));
                       binding.getAdp().notifyDataSetChanged();
                   });
               } catch (JSONException e) {
                   e.printStackTrace();
               }
           }
       });
    }
}